//防抖  用setTimeout延迟执行函数 当执行的时候存体延迟对象 清除掉
//升级第一次直接执行后续点的不执行

export function Debounce(fn, outTime, immediate = false) {
  let timer = null;
  return function callBack(...args) {
    if (timer) {
      clearTimeout(timer);
    }

    if (!timer && immediate) {
      fn.apply(this, args);
    }
    timer = setTimeout(() => {
      if (!immediate) {
        fn.apply(this, args);
      }
      //最后一次执行了 timer=null
      timer = null;
    }, outTime);
  };
}

//节流 记录函数上次执行的时间 获取现在的时间相减 是否大于设定的时间
export function throttle(func, delay) {
  let lastTime = 0;
  return function callBack(...args) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      func.apply(this, args);
      lastTime = now;
    }
  };
}

//滑动窗口执行promise
export async function queue(requestList, MAX_REQUEST) {
  let reslist = [];
  let count = 0;
  async function feachData(reqs) {
    try {
      const res = await reqs.req(reqs.params);
      reslist.push(res);
    } catch (err) {
      console.log(err, "---err");
    } finally {
      count--;
      processQueue();
    }
  }
  //循环取出接口执行
  async function processQueue() {
    while (count < MAX_REQUEST && requestList.length > 0) {
      count++;
      const reqs = requestList.pop();
      await feachData(reqs);
    }
  }
  await processQueue();
  return reslist;
}
//手写promise
// export class XPromise {
//   constructor() {}
// }
export class MyPromise {
  constructor(executor) {
    this.status = "pending"; // 初始状态
    this.value = undefined; // 成功时的值
    this.reason = undefined; // 失败时的原因
    this.onFulfilledCallbacks = []; // 成功回调队列
    this.onRejectedCallbacks = []; // 失败回调队列

    const resolve = (value) => {
      if (this.status === "pending") {
        this.status = "fulfilled";
        this.value = value;
        this.onFulfilledCallbacks.forEach((fn) => fn()); // 执行成功回调
      }
    };

    const reject = (reason) => {
      if (this.status === "pending") {
        this.status = "rejected";
        this.reason = reason;
        this.onRejectedCallbacks.forEach((fn) => fn()); // 执行失败回调
      }
    };

    try {
      executor(resolve, reject); // 执行 executor
    } catch (error) {
      reject(error); // 捕获 executor 中的错误
    }
  }

  then(onFulfilled, onRejected) {
    if (this.status === "fulfilled") {
      onFulfilled(this.value); // 直接调用成功回调
    }
    if (this.status === "rejected") {
      onRejected(this.reason); // 直接调用失败回调
    }
    if (this.status === "pending") {
      // console.log("----等待状态");

      // 如果是 pending 状态，将回调放入队列
      this.onFulfilledCallbacks.push(() => onFulfilled(this.value));
      this.onRejectedCallbacks.push(() => onRejected(this.reason));
    }
  }

  static all(promises) {
    return new MyPromise((resolve, reject) => {
      const results = []; // 存储所有 Promise 的结果
      let completedCount = 0; // 完成的 Promise 数量

      promises.forEach((promise, index) => {
        promise.then(
          (value) => {
            results[index] = value; // 存储成功结果
            completedCount++;
            if (completedCount === promises.length) {
              resolve(results); // 所有 Promise 完成时 resolve
            }
          },
          (reason) => {
            reject(reason); // 任何一个 Promise 失败时 reject
          },
        );
      });
    });
  }

  static race(promises) {
    return new MyPromise((resolve, reject) => {
      promises.forEach((promise) => {
        promise.then(
          (value) => {
            resolve(value); // 第一个完成的 Promise 成功时 resolve
          },
          (reason) => {
            reject(reason); // 第一个完成的 Promise 失败时 reject
          },
        );
      });
    });
  }
}

export class XPromise {
  constructor(executor) {
    this.status = "pedding";
    this.resultValue = undefined;
    this.rejectValue = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];
    const reslove = (value) => {
      if (this.status === "pedding") {
        this.status = "fulfilled";
        this.resultValue = value;
        console.log(this.onFulfilledCallbacks, "------rsss");

        this.onFulfilledCallbacks.forEach((fn) => fn());
      }
    };
    const reject = (err) => {
      if (this.status === "pedding") {
        this.status = "rejected";
        this.rejectValue = err;
        this.onRejectedCallbacks.forEach((fn) => fn());
      }
    };
    try {
      executor(reslove, reject);
    } catch (err) {
      reject(err);
    }
  }
  then(onFullfiled, onRejected) {
    if (this.status === "pedding") {
      this.onFulfilledCallbacks.push(() => onFullfiled(this.resultValue));
      this.onRejectedCallbacks.push(() => onRejected(this.rejectValue));
    }
    if (this.status === "fulfilled") {
      onFullfiled(this.value);
    }
    if (this.status === "rejected") {
      onRejected(this.rejectValue);
    }
  }
  all(promises) {
    return new XPromise((reslove, reject) => {
      
    });
  }
}
